package publish;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("162.14.99.141");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        connectionFactory.setVirtualHost("ty");
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        //声明交换机
        /**
         * Exchange.DeclareOk exchangeDeclare(String exchange,
         *         BuiltinExchangeType type,
         *         boolean durable,
         *         boolean autoDelete,
         *         boolean internal,
         *         Map<String, Object> arguments)
         * 参数介绍
         * exchange：交换机的名称（如 "order_events"）
         * type：交换机的类型，决定路由规则
         * durable：交换机是否持久化
         * autoDelete：当所有绑定的队列都解除绑定时，是否自动删除交换机
         * internal：是否为内部交换机（不可直接被生产者发布消息只能通过其他交换机路由到该交换机）
         * arguments：交换机的额外参数
         */
        channel.exchangeDeclare("fanout.exchange", BuiltinExchangeType.FANOUT, true, false, false, null);

        channel.queueDeclare("fanout.queue1", true, false, false, null);
        channel.queueDeclare("fanout.queue2", true, false, false, null);

        //交换机和队列进行绑定, 这里的routing key 可以为任意字符串
        channel.queueBind("fanout.queue1", "fanout.exchange", "3");
        channel.queueBind("fanout.queue2", "fanout.exchange", "1");

        for (int i = 0; i < 50; i++) {
            //这里的routing key 为任意字符串 都会把消息发送到交换机所绑定的队列上
            channel.basicPublish("fanout.exchange", "4", null, ("msg" + i).getBytes());
        }

        channel.close();
        connection.close();
    }
}
